/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

import Facade.AccountFacadeLocal;
import Facade.BankTransactionFacadeLocal;
import Facade.CurrencyFacadeLocal;
import Facade.CustomerFacadeLocal;
import Facade.ManagerLocal;
import entity.Account;
import entity.CurrencyEE;
import entity.Customer;
import java.math.BigDecimal;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.el.ELException;
import javax.faces.component.html.HtmlInputHidden;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.component.html.HtmlSelectOneMenu;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.persistence.NoResultException;
import util.JsfUtil;

/**
 *
 * @author Vojtisek
 */
public class AccountManagedBean {

    @EJB
    private ManagerLocal managerBean;
    @EJB
    private CurrencyFacadeLocal currencyFacadeBean;
    @EJB
    private BankTransactionFacadeLocal bankTransactionFacade;
    @EJB
    private AccountFacadeLocal accountFacade;
    private CurrencyEE currency;
    private Integer customerId;
    private Integer accountId;
    BigDecimal totalBalance;
    private static final Logger logger = Logger.getLogger("AccountManagedBean");
    private BigDecimal balance;

    public String create() throws Exception {
        try {
            Account foo = new Account();
            foo.setCurrency(currency);
            accountFacade.createAccount(foo);
            JsfUtil.addSuccessMessage("[" + new Time(new java.util.Date().getTime()) + "] Account was successfully created.");
        } catch (Exception e) {
            JsfUtil.ensureAddErrorMessage(e, "Persistance error: " + e.toString());
            logger.log(Level.SEVERE, e.getMessage(), e);
            return null;
        }
        return null;
    }

    public Collection<Account> getAccounts() {
        try {
            return accountFacade.getAccounts();
        } catch (Exception e) {
            JsfUtil.addErrorMessage("Persistance error: " + e.toString());
            logger.log(Level.SEVERE, e.getMessage(), e);
            return null;
        }
    }

    public boolean getInitManagerViewDetails() {
        if (accountId != null && customerId == null) {
            try {
                Account c = managerBean.getAccount(accountId);
                customerId = c.getOwner().getId();
                balance = c.getBalance();
                currency = c.getCurrency();
            } catch (Exception ex) {
                Logger.getLogger(AccountManagedBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return true;
    }

    public Collection<Account> getCustomerAccounts() {
        try {
            return managerBean.getCustomerAccounts(customerId);
        } catch (Exception e) {
            JsfUtil.addErrorMessage("Persistance error: " + e.toString());
            logger.log(Level.SEVERE, e.getMessage(), e);
            return null;
        }
    }

    public Collection<Account> getAllAccounts() {
        try {
            return managerBean.getAllAccounts();
        } catch (Exception ex) {
            JsfUtil.ensureAddErrorMessage(ex, "Persistance error: " + ex.getMessage());
            logger.log(Level.SEVERE, ex.getMessage(), ex);
        }
        return null;
    }

    public BigDecimal getTotalBalance() {
        try {
            if (currency == null) {
                currency = currencyFacadeBean.find("CZK");
            }
            totalBalance = bankTransactionFacade.getTotalBalance(currency);
            return totalBalance;
        } catch (Exception ex) {
            logger.log(Level.SEVERE, ex.getMessage(), ex);
        }
        return null;
    }

    public void processUpdate(ValueChangeEvent parameter) {
        PhaseId phaseId = parameter.getPhaseId();

        if (phaseId.equals(PhaseId.ANY_PHASE)) {
            parameter.setPhaseId(PhaseId.UPDATE_MODEL_VALUES);
            parameter.queue();
        } else if (phaseId.equals(PhaseId.UPDATE_MODEL_VALUES)) {
            try {
                if (customerId != null) {
                    totalBalance = bankTransactionFacade.getTotalBalance(currency);
                }
            } catch (Exception ex) {
                logger.log(Level.SEVERE, ex.getMessage(), ex);
            }
//        FacesContext.getCurrentInstance().renderResponse();
        }

    }

    public Collection<SelectItem> getCurrencyChoices() {
        try {
            Collection<SelectItem> items = new ArrayList<SelectItem>();
            for (CurrencyEE d : currencyFacadeBean.findAll()) {
                items.add(new SelectItem(d, d.name()));
            }
            return items;
        } catch (Exception ex) {
            Logger.getLogger(AccountManagedBean.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    public void setAccountId(Integer accountId) {
        this.accountId = accountId;
    }

    public void setCustomerId(Integer customerId) {
        if (customerId != null) {
            this.customerId = customerId;
        }
    }

    public CurrencyEE getCurrency() {
        return currency;
    }

    public void setCurrency(CurrencyEE currency) {
        this.currency = currency;
    }

    public Integer getCustomerId() {
        return customerId;
    }

    public Integer getAccountId() {
        return accountId;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }
}
